/*
 * The MIT License
 *
 * Copyright 2014 David Rodenas Pico.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package edu.uoc.sd.fr14.comp;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import edu.uoc.sd.fr14.mesg.Message;
import edu.uoc.sd.fr14.mesg.TargetId;
import java.net.InetSocketAddress;
import java.util.HashSet;
import java.util.Set;

/**
 * Component that sends messages to a remote socket.
 * 
 * Input:
 * - input: messages to send to remote
 * 
 * 
 * @author drodenas
 */
public class SocketRemoteComponent extends Component {

    private static final edu.uoc.sd.fr14.model.Logger log = edu.uoc.sd.fr14.model.Logger.get("RemoteComponent");
    
    private final Set<TargetId> targets;
    private final InetSocketAddress address;
    private volatile Socket socket;
    private volatile ObjectOutputStream output;
    
    public SocketRemoteComponent(Set<TargetId> targets, InetSocketAddress address) {
        super("remote-"+address);
        if (address == null) throw new NullPointerException("Illegal argument: address cannot be null");
        
        this.address = address;
        this.targets = new HashSet<>(targets);
    }
    
    @Override
    public void stop() {
        super.stop();
        
        // socket is no more needed
        try { socket.close(); } catch (NullPointerException | IOException ex) {}
    }

    @Override
    protected void process(Message message) {
        if (!targets.contains(message.getTarget())) return;
        
        // this method is single threaded
        try {
            if (socket == null) {
                socket = new Socket(address.getAddress(), address.getPort());
                output = new ObjectOutputStream(socket.getOutputStream());
                log.debug(address, "opened remote socket at:"+socket.getRemoteSocketAddress());
            }
            
            log.debug(address, "sending '"+message+"'");
            output.writeObject(message);
            output.flush();
        } catch (IOException ex) {
            Logger.getLogger(SocketRemoteComponent.class.getName()).log(Level.SEVERE, "socket remote to "+address+" for targets:"+targets, ex);
            // a small sleep to not consume too many resources
            try { Thread.sleep(4000); } catch (InterruptedException ex1) {}
            // if not stopped try to restart the service, next time
            try { output.close(); } catch (IOException | NullPointerException ex1) {}
            try { socket.close(); } catch (IOException | NullPointerException ex1) {}
            socket = null;
        }
    }
    
}
